from fastapi import APIRouter, Request,Query
from model import db
from model.user import User
from controller.rtn import Rtn
from model.question import Question
from model.user import UserQuestion,UserCommit,UserQuestionOption
from model.question import QuestionOption,Question,vali_date_and_hour
from sqlalchemy.orm import selectinload
from sqlalchemy import func
from pydantic import BaseModel,Field
from model.config import get_config
from datetime import datetime
from exception import JsonException
from fastapi.encoders import jsonable_encoder

router = APIRouter()


@router.get("/test")
async def test(request: Request):

    return 123123


@router.get("/list", summary="题目列表")
async def list1(
        request: Request,
        page: int = Query(1, ge=1, le=10000), 
        limit: int = Query(10, ge=1, le=10000),
):
    list_limit = 5
    user:User = request.state.userInfo

    with db.Session() as session:

        history_list = session.query(UserQuestion).filter(
            UserQuestion.user_id == user.id
        ).limit(1000).all()
        
        history_query_ids = []
        for item in history_list:
            history_query_ids.append(item.question_id)

        ####
        list = session.query(Question).options(selectinload(Question.options)).filter(
            Question.id.notin_(history_query_ids),
        ).order_by(
            func.random()).limit(list_limit).all()

        list2 = jsonable_encoder(list)
        for ques in list2:
            is_trues = []
            for options in ques["options"]:
                if options["is_true"] == "true":
                    is_trues.append(options["ind"])
            ques["isRight"] = is_trues

    return Rtn({
        "list": list2,
    })



#
class questionOption(BaseModel):
    id: int = Field(description='选项ID')
    is_true: str = Field(description='是否正确',max_length=20)
    selected: str = Field(description='用户是否选中',max_length=20)
    content: str = Field(description='用户是否选中')

class questionItem(BaseModel):
    id: int = Field(default=0, description='题目ID')
    is_true: str = Field(default="", description='是否正确',max_length=20)
    type: str = Field(default="", description='类型')
    content: str = Field(default="", description='题目')
    options: list[questionOption] = Field(default=[], description='选项', max_length=20)

class commitReq(BaseModel):
    questions:list[questionItem] = Field(default=[], description='提交的问题', min_length=1 ,max_length=20)

@router.post("/commit", summary="答题")
async def commit(
        request: Request,
        commitReq: commitReq, 
):
    user:User = request.state.userInfo


    conf = get_config()

    vali = vali_date_and_hour(conf)
    if not vali:
        raise JsonException("不在活动时间内，请勿答题")

    day_commit_limit = conf.day_commit_limit
    
    now = datetime.now()
    date_str = now.strftime('%Y-%m-%d')

    all_user_question_true_count = 0
    user_question_true_count = 0
    with db.Session() as session:
        # 查询用户今日提交的次数
        commit_count = session.query(UserCommit).filter(
            UserCommit.user_id == user.id,
            UserCommit.created_time >= date_str
        ).limit(1000).count()

        if commit_count + 1 > day_commit_limit:
            raise JsonException("今日提交次数已达上限", 400)

        # 消耗一次机会
        one = UserCommit()
        one.user_id = user.id
        session.add(one)
        session.commit()

        # 标记是否正确
        for ques in commitReq.questions:
            # 默认为正确
            ques.is_true = "true"
            for option in ques.options:
                if option.selected != option.is_true:
                    ques.is_true = "false"

            if ques.is_true == "true":
               user_question_true_count += 1

            two = UserQuestion()
            two.user_commit_id = one.id
            two.user_id = user.id
            two.question_id = ques.id
            two.is_true = ques.is_true
            two.type = ques.type
            two.content = ques.content

            session.add(two)
            session.commit()
            user_question_id = two.id

            
            # 记录options
            for option in ques.options:
                three = UserQuestionOption()
                three.user_id = user.id
                three.selected = option.selected
                three.content = option.content
                three.is_true = option.is_true
                three.user_question_id = user_question_id
                session.add(three)

        # 给用户增加分数
        u =  session.query(User).filter(
            User.id == user.id
        ).first()

        u.true_question_count = int(u.true_question_count) + user_question_true_count
        session.commit()
        all_user_question_true_count = u.true_question_count

        # 用户今日提交次数
        query = session.query(UserCommit).filter(
            UserCommit.user_id == user.id,
            UserCommit.created_time >= date_str,
        )
        user_today_commit_count = query.count()


    return Rtn({
        "trueQuesCount":user_question_true_count,
        "getPoint":user_question_true_count * conf.point_k,
        "allPoint":all_user_question_true_count * conf.point_k,

        "user_today_commit_count":user_today_commit_count,
        "day_commit_limit":conf.day_commit_limit,
    })

#
class importQuestionOption(BaseModel):
    is_true: str = Field(description='是否正确',max_length=20)
    ind: str = Field(description='序号')
    content: str = Field(description='选项内容')

class importQuestionItem(BaseModel):
    type: str = Field(default="", description='类型')
    content: str = Field(default="", description='题目')
    options: list[importQuestionOption] = Field(default=[], description='选项', max_length=20)

class importReq(BaseModel):
    questions:list[importQuestionItem] = Field(default=[], description='录入的题目列表', min_length=1 ,max_length=500)

@router.post("/import", summary="数据导入")
async def import1(
        request: Request,
        commitReq: importReq, 
):
    user:User = request.state.userInfo

    with db.Session() as session:

        # 题目录入
        for ques in commitReq.questions:

            one = Question()
            one.type = ques.type
            one.content = ques.content
            one.order = 0
            session.add(one)
            session.commit()
            question_id = one.id

            # 记录options
            option_order  = 0
            for option in ques.options:
                option_order += 1
                two = QuestionOption()
                two.question_id = question_id
                two.ind = option.ind
                two.content = option.content
                two.selected = "false"
                two.is_true = option.is_true
                two.order = option_order
                session.add(two)

            session.commit()


    return Rtn()
